package com.lastproject.web.bean;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ComponentSystemEvent;

import com.lastproject.dto.EmailGroupDTO;
import com.lastproject.dto.UserDTO;
import com.lastproject.ejb.dao.CheckPermissionDAORemote;
import com.lastproject.ejb.dao.EmailGroupDAORemote;
import com.lastproject.ejb.dao.UserDAORemote;
import com.lastproject.web.comparators.UserByNameComparator;

public class ManageGroupsBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7007086206698071912L;

	private List<String> idUsers;

	private boolean alreadyExists;

	private boolean error;

	@EJB
	EmailGroupDAORemote emailGroupDAORemote;

	@EJB
	UserDAORemote userDAORemote;

	EmailGroupDTO emailGroupDTO;

	UserDTO userDTO;

	List<EmailGroupDTO> groups = new ArrayList<EmailGroupDTO>();

	List<UserDTO> userDTOList = new ArrayList<UserDTO>();

	private boolean hasPermission = true;
	private String noRights = "";

	
	@EJB
	CheckPermissionDAORemote checkPermissionDAORemote;
	
	public void preRenderView(ComponentSystemEvent event) {
        if (!checkPermissionDAORemote.hasSurveyManagementRights(true)){
        	FacesContext fc = FacesContext.getCurrentInstance();
        	ExternalContext ec = fc.getExternalContext();
        	try {
				ec.redirect("restrictedAccess.xhtml");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
    }
	
	public boolean isHasPermission() {
		return hasPermission;
	}

	public void setHasPermission(boolean hasPermission) {
		this.hasPermission = hasPermission;
	}

	public String getNoRights() {
		return noRights;
	}

	public void setNoRights(String noRights) {
		this.noRights = noRights;
	}

	public String edit(ActionEvent event) {
		emailGroupDTO = (EmailGroupDTO) event.getComponent().getAttributes()
				.get("currentGroup");
		return "";
	}

	public String editGroup() {
		return "addUsersToGroup.xhtml";
	}

	public String create() {

		List<EmailGroupDTO> allGroups = emailGroupDAORemote.findAll();
		EmailGroupDTO newGroup = new EmailGroupDTO();
		newGroup.setName(emailGroupDTO.getName());
		alreadyExists = false;
		for (EmailGroupDTO e : allGroups) {
			if (e.getName().equals(newGroup.getName()))
				alreadyExists = true;
		}

		if (alreadyExists == true) {
			emailGroupDTO.setName("");
			return "groupCreate.xhtml";
		}


		boolean ok = emailGroupDAORemote.create(true,newGroup);
		if (!ok){
			noRights = "You do not have the rights to create an email group!";
			hasPermission = false;
			return "groupCreate.xhtml";
		}

		emailGroupDTO = emailGroupDAORemote.findLastByName(emailGroupDTO
				.getName());

		emailGroupDTO.setName("");
		return "manageGroups.xhtml";
	}

	public String addUsers() {
		String returnUrl = "manageGroups.xhtml";
		error = false;

		//get the list of users already in this group
		List<UserDTO> usersInGroup = emailGroupDTO.getUsers();
		if (usersInGroup == null) {
			usersInGroup = new ArrayList<UserDTO>();
		}

		// convert all id's from String format to integer format, and set the error flag if something went wrong
		List<Integer> intIds = getIntegerIds(idUsers);
		//if the flag is set to true, return
		if(error){
			return returnUrl;
		}

		List<UserDTO> usersToBeAdded = userDAORemote.findByMultipleId(intIds);
		usersInGroup.addAll(usersToBeAdded);
		Collections.sort(usersInGroup, new UserByNameComparator());
		emailGroupDTO.setUsers(usersInGroup);
		emailGroupDAORemote.edit(true,emailGroupDTO);

		// remove from the availability list the users already added
		//		userDTOList.removeAll(usersInGroup);


		return returnUrl;
	}

	public String removeUsers() {
		String returnUrl = "manageGroups.xhtml";
		error = false;
		List<Integer> idUsersInt = getIntegerIds(idUsers);
		if(error){
			return returnUrl;
		}
		List<UserDTO> usersToBeRemoved = userDAORemote.findByMultipleId(idUsersInt);

		List<UserDTO> usersInGroup = new ArrayList<UserDTO>();
		usersInGroup = emailGroupDTO.getUsers();

		List<UserDTO> updatedList = new ArrayList<UserDTO>();
		for(UserDTO userInGroup : usersInGroup){
			boolean found = false;
			for(UserDTO userToBeRemoved : usersToBeRemoved){
				if(userToBeRemoved.getId() == userInGroup.getId()){
					found = true;
					break;
				}
			}
			if(!found){
				updatedList.add(userInGroup);
			}
		}

		emailGroupDTO.setUsers(updatedList);
		emailGroupDAORemote.edit(true,emailGroupDTO);


		return returnUrl;
	}

	/**
	 * convert all IDs into Integer format, and set the error flag is something went wrong
	 * @param stringIds
	 * @return a list of integers, representing the IDs
	 */
	private List<Integer> getIntegerIds(List<String> stringIds){
		List<Integer> intIds = new ArrayList<Integer>();
		for(String idString : stringIds){
			int idUser;
			try{
				idUser = Integer.parseInt(idString);
			}catch(NumberFormatException nfe){
				idUser = -1;}
			if(idUser < 1){
				error = true;
				break;
			}else{
				intIds.add(idUser);
			}
		}
		return intIds;
	}


	public String back(){
		emailGroupDTO.setName("");
		alreadyExists = false;
		error = false;
		return "manageGroups.xhtml";
	}

	public EmailGroupDTO getEmailGroupDTO() {
		return emailGroupDTO;
	}

	public void setEmailGroupDTO(EmailGroupDTO emailGroupDTO) {
		this.emailGroupDTO = emailGroupDTO;
	}

	public UserDTO getUserDTO() {
		return userDTO;
	}

	public void setUserDTO(UserDTO userDTO) {
		this.userDTO = userDTO;
	}

	public List<EmailGroupDTO> getGroups() {
		return emailGroupDAORemote.findAll();
	}

	public void setGroups(List<EmailGroupDTO> groups) {
		this.groups = groups;
	}

	public List<String> getIdUsers() {
		return idUsers;
	}

	public void setIdUsers(List<String> idUsers) {
		this.idUsers = idUsers;
	}

	public List<UserDTO> getUserDTOList() {
		userDTOList = userDAORemote.getAll();
		List<UserDTO> isInGroupList = new ArrayList<UserDTO>();
		isInGroupList = emailGroupDTO.getUsers();
		List<UserDTO> newList = new ArrayList<UserDTO>();

		if (isInGroupList.size() == 0) {
			return userDTOList;
		}

		for (UserDTO user : userDTOList) {
			boolean is = false;
			for (UserDTO u : isInGroupList) {
				if (user.getId() == u.getId())
					is = true;
			}
			if (is == false)
				newList.add(user);
		}

		return newList;
	}

	public void setUserDTOList(List<UserDTO> userDTOList) {
		this.userDTOList = userDTOList;
	}

	public boolean isAlreadyExists() {
		return alreadyExists;
	}

	public void setAlreadyExists(boolean alreadyExists) {
		this.alreadyExists = alreadyExists;
	}

	public boolean isError() {
		return error;
	}

	public void setError(boolean error) {
		this.error = error;
	}

}
